package com.s2paganini.pv3d
{
	import flash.display.*;
	import flash.events.*;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.utils.getTimer;		

	public class FlashFPS extends Sprite {
		private var theBar : Sprite = new Sprite();
		private var time : Number;
		private var frameTime : Number;
		private var prevFrameTime : Number = getTimer();
		private var secondTime : Number;
		private var prevSecondTime : Number = getTimer();
		private var frames : Number = 0;
		private var theFPS : String = "...";
		private var other : String = "";
		private var memory : String;
		private var which : String;
		private var fps_text : TextField;
		private var format : TextFormat;

		public function FlashFPS()
		{
			stage.align = StageAlign.TOP_LEFT;
			which = "kb";
			createElements();
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function createElements() : void
		{
			theBar.x = 1;
			theBar.graphics.beginFill(0x999999, 1);
			theBar.graphics.drawRect(0, 0, 75, 1.5);
			theBar.graphics.endFill();
			addChild(theBar);
						
			format = new TextFormat();
			format.font = "Verdana";
			format.size = 9;
			format.color = 0xcccccc;
			
			fps_text = new TextField();
			fps_text.autoSize = TextFieldAutoSize.LEFT;
			fps_text.defaultTextFormat = format;
			
			addChild(fps_text);
		}

		public function onEnterFrame(e : Event) : void
		{
			time = getTimer();
		
			frameTime = time - prevFrameTime;
			secondTime = time - prevSecondTime;
		
			if(secondTime >= 1000) {
				theFPS = frames.toString();
				frames = 0;
				prevSecondTime = time;
			} else {
				frames++;
			}
			prevFrameTime = time;

			if(which == "b") {
				memory = flash.system.System.totalMemory.toPrecision(4) + " bytes";
			} else if(which == "kb") {
				memory = (flash.system.System.totalMemory / 1000).toPrecision(4) + " kbs";
			} else if (which == "mb") {
				memory = (flash.system.System.totalMemory / 1000000).toPrecision(4) + " mbs";
			}
			
			fps_text.text = "framerate: " + theFPS + " fps / " + frameTime + "ms . memory: " + memory + " . " + other.toString();
			theBar.scaleX = theBar.scaleX - ((theBar.scaleX - (frameTime / 10)) / 5);
		}

		public function update(x : String) : void
		{
			other = x;
		}
	}
}